<?php
namespace app\admin\controller;

use app\api\model\Image;
use app\api\model\Product as ProductModel;
use app\api\model\Category as CategoryModel;
use app\api\model\ProductProperty as Property;
use app\api\model\ProductImage;
use app\api\model\ProductProperty;
use app\api\service\Upload;

class Product extends Base
{
    public function all()
    {
        return view('all');
    }

    public function getProductAll()
    {
        $params = request()->param();
        $where = [];
        if( $params['name'] ){
            $where['name'] = ['like','%'.$params['name'].'%'];
        }
        $total = ProductModel::where($where)->count();
        $list = ProductModel::all(function ($query) use ($where,$params){
            $query->where($where);
            $query->limit($params['offset'],$params['limit']);
        },'category');

        return ['code' => 200, 'msg' => 'ok' ,'data' => compact('total','list')];
    }

    public function add()
    {
        $category = CategoryModel::all();
        return view('add',compact('category'));
    }

    public function addProduct()
    {
        $main = request()->only(['name','price','stock','category_id']);

        unset($_FILES['fileImage']);
        $result = Upload::upload($_FILES);
        if( $result['code'] == 200 ){
            $m = Image::create([
                'url'   => $result['data']['main_img_url'],
                'from'  => 1
            ]);
            $main['main_img_url'] = $result['data']['main_img_url'];
            $main['img_id'] = $m->getLastInsID();
        }else{
            $this->error($result['msg']);
            exit;
        }
        $id = ProductModel::create($main)->getLastInsID();

        //产品详情图片添加
        $file = request()->only('file')['file'];
        foreach ($file as $k=>$v){
            $result = Upload::uploadBase64($v);
            $img_id = Image::create([
                'url'   => $result['data'],
                'from'  => 1
            ])->getLastInsID();
            $img = [
                'product_id' => $id,
                'order'      => $k+1,
                'img_id'     => $img_id
            ];
            ProductImage::create($img);
        }

        //产品属性添加
        list($property_name,$property_detail) = array_values(request()->only(['property_name','property_detail']));
        foreach ($property_name as $k=>$v){
            if( $v ){
                ProductProperty::create([
                    'name'      => $v,
                    'detail'    => $property_detail[$k],
                    'product_id'=> $id,
                ]);
            }
        }

        $this->redirect('/admin/product/all',['success' => '添加产品成功']);
    }

    public function edit()
    {

        $id = request()->get('id');
        $category = CategoryModel::all();
        $product = ProductModel::get($id,['imgs' => function($query){
            $query->with('imgUrl');
        },'category','properties'])->toArray();

        return view('edit',compact('product','category'));
    }

    public function updateProduct()
    {
        $params = request()->param();

        $id = $params['id'];
        $main = array_only($params,['name','price','stock','category_id']);
        if( $_FILES['main_img_url']['error'] == 0 ){
            unset($_FILES['fileImage']);
            $result = Upload::upload($_FILES);
            if( $result['code'] == 200 ){
                $m = Image::create([
                    'url'   => $result['data']['main_img_url'],
                    'from'  => 1
                ]);
                $main['main_img_url'] = $result['data']['main_img_url'];
                $main['img_id'] = $m->getLastInsID();
            }else{
                $this->error($result['msg']);
                exit;
            }
        }
        ProductModel::update($main,['id' => $id]);

        //产品属性修改
        ProductProperty::destroy(['product_id' => $id]);
        list($property_name,$property_detail) = array_values(array_only($params,['property_name','property_detail']));
        if( $property_name && $property_detail ) {
            foreach ($property_name as $k => $v) {
                if ($v) {
                    ProductProperty::create([
                        'name' => $v,
                        'detail' => $property_detail[$k],
                        'product_id' => $id,
                    ]);
                }
            }
        }


        //产品详情图片添加
        //旧
        $img_id = isset(array_only($params,['img_id'])['img_id'])?array_only($params,['img_id'])['img_id']:[];
        $result = ProductImage::all(['product_id' => $id],'img_url')->toArray();
        if( $result ){
            foreach ($result as $k=>$v){
                $img[] = $v['img_url']['url'];
            }
            $diff = array_diff_assoc($img,$img_id);
            foreach ( $diff as $k=>$v ){
                $i_id = $result[$k]['id'];
                ProductImage::destroy(['id' => $i_id]);
            }
        }



        //新
        $file = isset(array_only($params,['file'])['file'])?array_only($params,['file'])['file']:[];
        if( $file ){
            foreach ($file as $k=>$v){
                $result = Upload::uploadBase64($v);
                $img_id = Image::create([
                    'url'   => $result['data'],
                    'from'  => 1
                ])->getLastInsID();
                $img = [
                    'product_id' => $id,
                    'order'      => $k+1,
                    'img_id'     => $img_id
                ];
                ProductImage::create($img);
            }
        }


        $this->redirect('/admin/product/all',['success' => '添加产品成功']);

    }
}